package com.ityj.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.ityj.yygh.enums.PaymentTypeEnum;
import com.ityj.yygh.enums.RefundStatusEnum;
import com.ityj.yygh.model.order.OrderInfo;
import com.ityj.yygh.model.order.PaymentInfo;
import com.ityj.yygh.model.order.RefundInfo;
import com.ityj.yygh.order.service.OrderService;
import com.ityj.yygh.order.service.PaymentInfoService;
import com.ityj.yygh.order.service.RefundInfoService;
import com.ityj.yygh.order.service.WeiXinService;
import com.ityj.yygh.order.utils.HttpClient;
import com.ityj.yygh.order.utils.WxPayPropertiesUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class WeiXinServiceImpl implements WeiXinService {

    @Autowired
    private OrderService orderService;

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PaymentInfoService paymentService;

    @Autowired
    private RefundInfoService refundInfoService;

    @Override
    public Map<String, Object> createNative(Long orderId) {
        Map<String, Object> payMap = (Map<String, Object>) redisTemplate.opsForValue().get(String.valueOf(orderId));
        if (payMap != null) {
            log.info("Native code has generated!");
            return payMap;
        }

        // 根据id获取订单信息
        OrderInfo orderInfo = orderService.getOrderInfo(orderId);
        // 保存交易记录
        paymentInfoService.savePaymentInfo(orderInfo, PaymentTypeEnum.WEIXIN.getStatus());

        // 调用接口，获取微信支付相关数据
        // 1.设置参数
        Map<String, String> weiXinMap = new HashMap<>();
        weiXinMap.put("appid", WxPayPropertiesUtil.APP_ID);
        weiXinMap.put("mch_id", WxPayPropertiesUtil.PARTNER);
        weiXinMap.put("nonce_str", WXPayUtil.generateNonceStr());
        String body = orderInfo.getReserveDate() + "就诊" + orderInfo.getDepname();
        weiXinMap.put("body", body);
        weiXinMap.put("out_trade_no", orderInfo.getOutTradeNo());
        //paramMap.put("total_fee", order.getAmount().multiply(new BigDecimal("100")).longValue()+"");
        weiXinMap.put("total_fee", "1");   // 用于测试
        weiXinMap.put("spbill_create_ip", "127.0.0.1");
        weiXinMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");
        weiXinMap.put("trade_type", "NATIVE");
        try {
            // 2. HTTPClient来根据URL访问第三方接口并且传递参数
            HttpClient client = new HttpClient(WXPayConstants.UNIFIEDORDER_URL);
            //client设置参数
            client.setXmlParam(WXPayUtil.generateSignedXml(weiXinMap, WxPayPropertiesUtil.PARTNER_KEY));
            client.setHttps(true);
            client.post();

            //3、返回第三方的数据
            String content = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(content);
            //4、封装返回结果集
            Map<String, Object> map = new HashMap<>();
            map.put("orderId", orderId);
            map.put("totalFee", orderInfo.getAmount());
            map.put("resultCode", resultMap.get("result_code"));
            map.put("codeUrl", resultMap.get("code_url"));

            if (resultMap.get("result_code") != null) {
                //微信支付二维码2小时过期，可采取2小时未支付取消订单
                redisTemplate.opsForValue().set(String.valueOf(orderId), map, 120, TimeUnit.MINUTES);
            }
            return map;
        } catch (Exception e) {
            log.error("Error occurs:", e);
        }
        return null;
    }

    // 调用微信支付状态查询接口
    @Override
    public Map<String, String> queryPayStatus(Long orderId) {
        OrderInfo orderInfo = orderService.getOrderInfo(orderId);

        // 调用接口，获取微信支付的状态
        // 1.设置参数
        Map<String, String> weiXinMap = new HashMap<>();
        weiXinMap.put("appid", WxPayPropertiesUtil.APP_ID);
        weiXinMap.put("mch_id", WxPayPropertiesUtil.PARTNER);
        weiXinMap.put("out_trade_no", orderInfo.getOutTradeNo());
        weiXinMap.put("nonce_str", WXPayUtil.generateNonceStr());
        try {
            // 2. HTTPClient来根据URL访问第三方接口并且传递参数
            HttpClient client = new HttpClient(WXPayConstants.ORDERQUERY_URL);
            //client设置参数
            client.setXmlParam(WXPayUtil.generateSignedXml(weiXinMap, WxPayPropertiesUtil.PARTNER_KEY));
            client.setHttps(true);
            client.post();

            //3、返回第三方的数据
            String content = client.getContent();
            return WXPayUtil.xmlToMap(content);
        } catch (Exception e) {
            log.error("Error occurs:", e);
        }
        return null;
    }

    @Override
    public Boolean refund(Long orderId) {
        try {
            PaymentInfo paymentInfoQuery = paymentService.getPaymentInfo(orderId, PaymentTypeEnum.WEIXIN.getStatus());

            RefundInfo refundInfo = refundInfoService.saveRefundInfo(paymentInfoQuery);
            if (refundInfo.getRefundStatus().intValue() == RefundStatusEnum.REFUND.getStatus().intValue()) {
                return true;
            }
            Map<String, String> paramMap = new HashMap<>(8);
            paramMap.put("appid", WxPayPropertiesUtil.APP_ID);       //公众账号ID
            paramMap.put("mch_id", WxPayPropertiesUtil.PARTNER);   //商户编号
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            paramMap.put("transaction_id", paymentInfoQuery.getTradeNo()); //微信订单号
            paramMap.put("out_trade_no", paymentInfoQuery.getOutTradeNo()); //商户订单编号
            paramMap.put("out_refund_no", "tk" + paymentInfoQuery.getOutTradeNo()); //商户退款单号
            //       paramMap.put("total_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
            //       paramMap.put("refund_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee", "1");
            paramMap.put("refund_fee", "1");
            String paramXml = WXPayUtil.generateSignedXml(paramMap, WxPayPropertiesUtil.PARTNER_KEY);
            HttpClient client = new HttpClient(WXPayConstants.REFUND_URL);
            client.setXmlParam(paramXml);
            client.setHttps(true);
            client.setCert(true);
            client.setCertPassword(WxPayPropertiesUtil.PARTNER);
            client.post();
            //3、返回第三方的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            if (WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code"))) {
                refundInfo.setCallbackTime(new Date());
                refundInfo.setTradeNo(resultMap.get("refund_id"));
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());
                refundInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
                refundInfoService.updateById(refundInfo);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("Error occurred: ", e);
        }
        return false;
    }
}
